<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

$error = '';
$success = '';

// 获取教练分类列表
$db = db_connect();
$categoryStmt = $db->query("SELECT * FROM coach_categories WHERE status = 1 ORDER BY sort_order");
$categories = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = safe_input($_POST['name']);
    $gender = safe_input($_POST['gender']);
    $age = intval($_POST['age']);
    $phone = safe_input($_POST['phone']);
    $email = safe_input($_POST['email']);
    $category_id = intval($_POST['category_id']);
    $experience = intval($_POST['experience']);
    $price = floatval($_POST['price']);
    $description = safe_input($_POST['description']);
    $certification = safe_input($_POST['certification']);
    $achievement = safe_input($_POST['achievement']);
    $status = intval($_POST['status']);
    
    // 验证表单数据
    if (empty($name) || empty($phone)) {
        $error = '姓名和手机号不能为空';
    } elseif (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
        $error = '手机号格式不正确';
    } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '邮箱格式不正确';
    } elseif ($age < 18 || $age > 60) {
        $error = '年龄必须在18-60岁之间';
    } elseif ($price <= 0) {
        $error = '课程价格必须大于0';
    } else {
        try {
            // 处理头像上传
            $avatar = '';
            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $allowed = ['jpg', 'jpeg', 'png', 'gif'];
                $filename = $_FILES['avatar']['name'];
                $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                
                if (!in_array($ext, $allowed)) {
                    $error = '只允许上传 jpg, jpeg, png, gif 格式的图片';
                } else {
                    $upload_dir = '../api/user/uploads/coaches/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $new_filename = uniqid() . '.' . $ext;
                    if (move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_dir . $new_filename)) {
                        $avatar = 'uploads/coaches/' . $new_filename;
                    }
                }
            }
            
            if (empty($error)) {
                // 插入教练信息
                $stmt = $db->prepare("INSERT INTO coaches (name, avatar, gender, age, phone, email, category_id, 
                    experience, description, certification, achievement, price, status, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                
                $stmt->execute([
                    $name, $avatar, $gender, $age, $phone, $email, $category_id,
                    $experience, $description, $certification, $achievement, $price, $status
                ]);
                
                $success = '教练添加成功';
            }
        } catch(PDOException $e) {
            $error = '系统错误，请稍后再试';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加教练 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/dashboard.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>
    <div class="wrapper">
        <!-- 引入侧边栏 -->
        <?php include 'includes/sidebar.php'; ?>

        <!-- 主要内容区 -->
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>添加教练</h2>
                </div>
                <div class="header-right">
                    <a href="coaches.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </header>

            <div class="content">
                <div class="form-container">
                    <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="name">姓名 <span class="required">*</span></label>
                            <input type="text" id="name" name="name" required>
                        </div>

                        <div class="form-group">
                            <label for="avatar">头像</label>
                            <input type="file" id="avatar" name="avatar" accept="image/*">
                        </div>

                        <div class="form-group">
                            <label for="gender">性别 <span class="required">*</span></label>
                            <select id="gender" name="gender" required>
                                <option value="1">男</option>
                                <option value="2">女</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="age">年龄 <span class="required">*</span></label>
                            <input type="number" id="age" name="age" required min="18" max="60">
                        </div>

                        <div class="form-group">
                            <label for="phone">手机号 <span class="required">*</span></label>
                            <input type="text" id="phone" name="phone" required>
                        </div>

                        <div class="form-group">
                            <label for="email">邮箱</label>
                            <input type="email" id="email" name="email">
                        </div>

                        <div class="form-group">
                            <label for="category_id">专长分类 <span class="required">*</span></label>
                            <select id="category_id" name="category_id" required>
                                <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>">
                                    <?php echo htmlspecialchars($category['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="experience">教龄(年) <span class="required">*</span></label>
                            <input type="number" id="experience" name="experience" required min="0">
                        </div>

                        <div class="form-group">
                            <label for="price">课程价格 <span class="required">*</span></label>
                            <input type="number" id="price" name="price" required min="0" step="0.01">
                        </div>

                        <div class="form-group">
                            <label for="description">个人简介</label>
                            <textarea id="description" name="description" rows="4"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="certification">资质证书</label>
                            <textarea id="certification" name="certification" rows="4"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="achievement">个人成就</label>
                            <textarea id="achievement" name="achievement" rows="4"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="status">状态 <span class="required">*</span></label>
                            <select id="status" name="status" required>
                                <option value="1">正常</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 